/*
 * mutex.h
 *
 *  Created on: 2008-9-18
 *      Author: fanliangliang
 */

#ifndef MUTEX_H_
#define MUTEX_H_

#include "config.h"

#if defined(PLATFORM_WIN32)

#include <windows.h>

BEGIN_NAMESPACE_TOXIC

class Mutex {
	CLASS_UNCOPYABLE(Mutex)
public:
	typedef CRITICAL_SECTION handle_type;

	Mutex() { InitializeCriticalSection(&_cs); }
	~Mutex() { DeleteCriticalSection(&_cs); }

	void lock() { EnterCriticalSection(&_cs); }
	void unlock() { LeaveCriticalSection(&_cs); }
	bool trylock() { return TryEnterCriticalSection(&_cs) == TRUE; }

	handle_type* internal() { return &_cs; }

private:
	CRITICAL_SECTION _cs;
};

END_NAMESPACE_TOXIC

#elif defined(PLATFORM_POSIX)

#include <pthread.h>

BEGIN_NAMESPACE_TOXIC

class Mutex {
	CLASS_UNCOPYABLE(Mutex)
public:
	typedef pthread_mutex_t handle_type;

	Mutex() { pthread_mutex_init(&_mutex, 0); }
	~Mutex() { pthread_mutex_destroy(&_mutex); }

	void lock() { pthread_mutex_lock(&_mutex); }
	void unlock() { pthread_mutex_unlock(&_mutex); }
	bool trylock() { return pthread_mutex_trylock(&_mutex) == 0; }

	handle_type* internal() { return &_mutex; }

private:
	pthread_mutex_t _mutex;
};

END_NAMESPACE_TOXIC

#else
#error "Mutex unavailable on this platform"
#endif

#endif /* MUTEX_H_ */
